import {InterceptedRequest, InterceptedResponse, Interceptor} from "ng2-interceptors";
import {Injectable, Injector} from "@angular/core";
import {Router} from "@angular/router";
import {Http} from "@angular/http";

@Injectable()
export class ServerURLInterceptor implements Interceptor {
  private http: Http;
  private router: Router;

  constructor(public injector: Injector) {
    setTimeout(() => {
      this.http = injector.get(Http);
      this.router = injector.get(Router);
    });
  }

  public interceptBefore(request: InterceptedRequest): InterceptedRequest {
    let headers = request.options.headers || new Headers();
    let accessToken = localStorage.getItem("accessToken");
    let oldAccessToken = headers.get('accessToken');
    if (!headers.get('Content-Type')) {
      headers.append('Content-Type', 'application/json');
    }
    if (!oldAccessToken && accessToken) {
      headers.append('accessToken', accessToken);
    }
    if (oldAccessToken && oldAccessToken != accessToken) {
      headers.delete('accessToken');
      headers.append('accessToken', accessToken);
    }
    return request;
  }

  public interceptAfter(response: InterceptedResponse): InterceptedResponse {
    return response;
  }
}
